package Linux五种IO模型.reactor2;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author coderFu
 * @create 2022/3/8
 */
public class NamedThreadFactory implements ThreadFactory {

    private final  ThreadGroup threadGroup;

    private final  AtomicInteger poolNumber = new AtomicInteger();

    private final  AtomicInteger threadNumber = new AtomicInteger();

    public final  String namePrefix;


    public NamedThreadFactory(String name){
        // 校验当前系统状态是否正常,并提供线程组
        SecurityManager s = System.getSecurityManager();
        threadGroup = (s != null)? s.getThreadGroup():
                Thread.currentThread().getThreadGroup();

        if (name == null){
            // 如果没有提供 那就使用 模式pool
            name = "pool";
        }
        namePrefix = name+"-"+poolNumber.getAndIncrement()+"-thread-";
    }




    @Override
    public Thread newThread(Runnable r) {

        Thread t = new Thread(threadGroup,r,
                namePrefix+threadNumber.getAndIncrement(),0);
        if (t.isDaemon()){
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY){
            // 所有线程的优先级初始为相同
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}
